package ssl;
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
import java.security.cert.*;
import java.math.BigInteger;

public class Server {

	private static SSLServerSocket serverSocket;
	
	public static void main(String args[]) throws Exception {
		try {
			SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
            serverSocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(Integer.parseInt(args[1]));
		}
		catch (Exception exception) {
			System.out.println("Error creating server socket");
			exception.printStackTrace();
		}
		if (args.length != 2) {
			System.out.println("Incorrect number of command line arguments");
			System.exit(0);
		}
		while (true) {
			Socket s = serverSocket.accept();
			SSLSession session = ((SSLSocket) s).getSession();
			Certificate[] cchain2 = session.getLocalCertificates();
			for (int i = 0; i < cchain2.length; i++) {
				System.out.println(((X509Certificate) cchain2[i]).getSubjectDN());
			}
			System.out.println("Peer host is " + session.getPeerHost());
	    	System.out.println("Cipher is " + session.getCipherSuite());
	    	System.out.println("Protocol is " + session.getProtocol());
	    	System.out.println("ID is " + new BigInteger(session.getId()));
	    	System.out.println("Session created in " + session.getCreationTime());
	    	System.out.println("Session accessed in " + session.getLastAccessedTime());
	    	
	    	OutputStream outs = s.getOutputStream();
	    	PrintStream pouts = new PrintStream(outs);
	    	InputStream ins = s.getInputStream();
	    	BufferedReader in = new BufferedReader(new InputStreamReader(ins));
	    	
	    	FileOutputStream fouts = new FileOutputStream(args[0]);
	    	int kk;
	    	while ((kk = ins.read()) != -1) {
	    		fouts.write(kk);
	    	}
	    	in.close();
	    	fouts.close();
		}
	}
}
